package com.banciyuan.bcywebview.biz.detail.goods;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.goods.order.confirmorder.ConfirmOrderActivity;
import com.banciyuan.bcywebview.biz.goods.shoppingcart.ShoppingCartHelper;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.currency.CurrencyUtil;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.BaseGoods;
import de.greenrobot.daoexample.model.DetailGoods;

/**
 * Created by squall on 2016/10/18.
 */

public class GoodsSelectActivity extends BaseActivity implements View.OnClickListener {

    private TextView add_car;
    private TextView buy_now;
    private TextView goods_nums;
    private ImageView miuns;
    private ImageView plus;
    private TextView goods_name;
    private TextView goods_price;
    private ImageView goods_img;
    private View goods_car_nums;
    private ImageView goods_close;
    private RelativeLayout main_container;
    private TextView show_phoneshell;
    private ImageView goods_img2;
    private TextView goods_comfirm;
    private FlowView category_container;
    private boolean is_animerunning;
    private DetailGoods detailGoods;
    private List<DetailGoods> dlist = new ArrayList<>();
    private String type = "all";
    private RequestQueue mQueue;
    private String select_decrption;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_select_activity);
        initArgs();
        initUi();
        initAction();
    }

    @Override
    protected void initArgs() {
        detailGoods = (DetailGoods) getIntent().getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        type = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        dlist = ShoppingCartHelper.getShoppingItems(this);
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initUi() {
        add_car = (TextView) findViewById(R.id.add_to_cars);
        buy_now = (TextView) findViewById(R.id.buy_now);
        goods_comfirm = (TextView) findViewById(R.id.comfirm);
        goods_img = (ImageView) findViewById(R.id.goods_header);
        goods_close = (ImageView) findViewById(R.id.goods_close);
        goods_nums = (TextView) findViewById(R.id.goods_nums);
        miuns = (ImageView) findViewById(R.id.minus);
        plus = (ImageView) findViewById(R.id.plus);
        goods_name = (TextView) findViewById(R.id.goods_name);
        goods_price = (TextView) findViewById(R.id.goods_price);
        main_container = (RelativeLayout) findViewById(R.id.main_container);
        goods_car_nums = findViewById(R.id.buy_car_num);
        show_phoneshell = (TextView) findViewById(R.id.click_show_view);
        goods_img2 = (ImageView) findViewById(R.id.goods_header_anime);
        category_container = (FlowView) findViewById(R.id.category_container);
        if (type.equals("all")) {
            goods_comfirm.setVisibility(View.GONE);
            add_car.setVisibility(View.VISIBLE);
            buy_now.setVisibility(View.VISIBLE);
        } else {
            goods_comfirm.setVisibility(View.VISIBLE);
            add_car.setVisibility(View.GONE);
            buy_now.setVisibility(View.GONE);
        }
        renderData();
    }

    private void renderData() {
        refreashBuyCar();
        if (StringUtil.notNullEqual(detailGoods.getZp_id(), "1")) {
            show_phoneshell.setVisibility(View.VISIBLE);
        } else {
            show_phoneshell.setVisibility(View.GONE);
        }
        if (detailGoods.getSelect_sku() != null) {
            goods_name.setText(String.format(getString(R.string.has_select), detailGoods.getSelect_sku().getDescription()));
        } else {
            goods_name.setText(getString(R.string.select_goods_unit));
        }
        if (!TextUtils.isEmpty(CurrencyUtil.getMoney(detailGoods.getBasic_price()))) {
            goods_price.setText(String.format(getString(R.string.price_format), CurrencyUtil.getMoney(detailGoods.getBasic_price())));
        }
        if (detailGoods.getCount() != 0) {
            goods_nums.setText(String.valueOf(detailGoods.getCount()));
        }
        if (!TextUtils.isEmpty(detailGoods.getCover())) {
            ImageLoader.getInstance().displayImage(detailGoods.getCover(), goods_img, ImageOptions.options);
            ImageLoader.getInstance().displayImage(detailGoods.getCover(), goods_img2, ImageOptions.options);
        }
        category_container.setHorizontalSpacing(UIUtils.dip2px(10, this));
        category_container.setVerticalSpacing(UIUtils.dip2px(15, this));
        category_container.removeAllViews();
        category_container.setVisibility(View.VISIBLE);
        for (int i = 0; i < detailGoods.getSku_data().size(); i++) {
            final View view = View.inflate(this, R.layout.goods_category_item, null);
            final TextView tv = (TextView) view.findViewById(R.id.item_name);
            tv.setTag(i);
            tv.setText(detailGoods.getSku_data().get(i).getDescription());
            final DetailGoods.Sku_list sku_list = detailGoods.getSku_data().get(i);
            final String add_price = sku_list.getAdd_price();
            if (detailGoods.getSelect_sku() != null && detailGoods.getSelect_sku().getZps_id().equals(sku_list.getZps_id())) {
                tv.setSelected(true);
                goods_name.setText(String.format(getString(R.string.has_select), tv.getText().toString()));
                select_decrption = tv.getText().toString();
            }
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tv.setSelected(!tv.isSelected());
                    if (tv.isSelected()) {
                        detailGoods.setSelect_sku(sku_list);
                        goods_name.setText(String.format(getString(R.string.has_select), tv.getText().toString()));
                        String result = String.valueOf(Integer.parseInt(detailGoods.getBasic_price()) + Integer.parseInt(add_price));
                        goods_price.setText(String.format(getString(R.string.price_format), CurrencyUtil.getMoney(result)));
                        select_decrption = tv.getText().toString();
                    } else {
                        detailGoods.setSelect_sku(null);
                        goods_name.setText(getString(R.string.select_goods_unit));
                        String result = String.valueOf(Integer.parseInt(detailGoods.getBasic_price()));
                        goods_price.setText(String.format(getString(R.string.price_format), CurrencyUtil.getMoney(result)));
                        select_decrption = "";
                    }
                    for (int j = 0; j < category_container.getChildCount(); j++) {
                        LinearLayout layout = (LinearLayout) category_container.getChildAt(j);
                        TextView tempTv = (TextView) layout.getChildAt(0);
                        if (tv.getTag() != tempTv.getTag()) {
                            tempTv.setSelected(false);
                        }
                    }
                }
            });
            category_container.addView(view);
        }
    }

    @Override
    protected void initAction() {
        add_car.setOnClickListener(this);
        buy_now.setOnClickListener(this);
        plus.setOnClickListener(this);
        miuns.setOnClickListener(this);
        goods_close.setOnClickListener(this);
        goods_comfirm.setOnClickListener(this);
        goods_img.setOnClickListener(this);
    }

    private void changeNum(int num) {
        int orgin = Integer.parseInt(goods_nums.getText().toString());
        int result = orgin + num;
        if (result == 1) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                miuns.setImageDrawable(getResources().getDrawable(R.drawable.minus_unclickable, getTheme()));
            } else {
                miuns.setImageDrawable(getResources().getDrawable(R.drawable.minus_unclickable));
            }
        } else if (result == 99) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                plus.setImageDrawable(getResources().getDrawable(R.drawable.plus_unclickable, getTheme()));
            } else {
                plus.setImageDrawable(getResources().getDrawable(R.drawable.plus_unclickable));
            }
        } else {
            if (orgin == 99) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                    miuns.setImageDrawable(getResources().getDrawable(R.drawable.minus_clickable, getTheme()));
                } else {
                    miuns.setImageDrawable(getResources().getDrawable(R.drawable.minus_clickable));
                }
            }
            if (orgin == 1) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                    plus.setImageDrawable(getResources().getDrawable(R.drawable.plus_clickable, getTheme()));
                } else {
                    plus.setImageDrawable(getResources().getDrawable(R.drawable.plus_clickable));
                }
            }
        }
        if (result >= 1 && result <= 99) {
            goods_nums.setText(String.valueOf(result));
            detailGoods.setCount(result);
        }
    }

    private void showImageAnime() {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) goods_img2.getLayoutParams();
        AnimatorSet animatorSet = new AnimatorSet();
        ObjectAnimator animator = ObjectAnimator.ofFloat(goods_img2, "rotation", 720).setDuration(800);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(goods_img2, "scaleX", 0.1f).setDuration(800);
        ObjectAnimator animator3 = ObjectAnimator.ofFloat(goods_img2, "scaleY", 0.1f).setDuration(800);
        ObjectAnimator animator4 = ObjectAnimator.ofFloat(goods_img2, "translationX", goods_img2.getRight() + lp.leftMargin + goods_img2.getWidth()).setDuration(800);
        ObjectAnimator animator5 = ObjectAnimator.ofFloat(goods_img2, "translationY", -goods_img2.getTop() - UIUtils.dip2px(70, GoodsSelectActivity.this) + lp.bottomMargin + UIUtils.dip2px(32, GoodsSelectActivity.this)).setDuration(800);
        animatorSet.playTogether(animator, animator2, animator3, animator4, animator5);
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                is_animerunning = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                goods_img2.setTranslationX(0);
                goods_img2.setTranslationY(UIUtils.dip2px(70, GoodsSelectActivity.this));
                goods_img2.setScaleX(1);
                goods_img2.setScaleY(1);
                goods_img2.setRotation(0);
                is_animerunning = false;
                refreashBuyCar();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animatorSet.start();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.goods_header:
                if (StringUtil.notNullEqual(detailGoods.getZp_id(), "1")) {
                    gotoShells();
                }
                break;
            case R.id.add_to_cars:
                if (!is_animerunning && addBuyCar()) {
                    showImageAnime();
                }
                break;
            case R.id.plus:
                changeNum(1);
                break;
            case R.id.minus:
                changeNum(-1);
                break;
            case R.id.goods_close:
                close();
                break;
            case R.id.buy_now:
                gotoOrder();
                break;
            case R.id.comfirm:
                if (type.equals("buy")) {
                    gotoOrder();
                } else {
                    if (!is_animerunning && addBuyCar()) {
                        showImageAnime();
                    }
                }
                break;
        }
    }

    private void gotoShells() {
        Intent intent = new Intent(this, GoodsShellImageActivity.class);
        intent.putExtra("decrption", select_decrption);
        intent.putExtra("detailGoods", detailGoods);
        startActivity(intent);
    }

    private void gotoOrder() {
        buy_now.setClickable(false);
        goods_comfirm.setClickable(false);
        if (null != detailGoods.getSelect_sku()) {
            List<BaseGoods> selectDetailGoods = new ArrayList<>();
            selectDetailGoods.add(new BaseGoods(detailGoods.getZg_id(), detailGoods.getSelect_sku().getZps_id(), detailGoods.getCount()));
            getPreOrder(selectDetailGoods);
        } else {
            MyToast.show(this, getString(R.string.select_goods));
            buy_now.setClickable(true);
            goods_comfirm.setClickable(true);
        }
    }

    private void getPreOrder(List<BaseGoods> selectDetailGoods) {
        String url = HttpUtils.BASE_URL + ZhipinApi.getPreCreateOrder();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.UPLOAD_DATA, new Gson().toJson(selectDetailGoods)));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, GoodsSelectActivity.this)) {
                        JSONObject result = new JSONObject(s);
                        JSONObject jsonObject = result.getJSONObject(HttpUtils.UPLOAD_DATA);
                        String cartId = jsonObject.getString("pre");
                        List<DetailGoods> delGoods = new Gson().fromJson(jsonObject.getString("del"), new TypeToken<List<DetailGoods>>() {
                        }.getType());
                        processPreOderResult(cartId, delGoods);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                buy_now.setClickable(true);
                goods_comfirm.setClickable(true);
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
                buy_now.setClickable(true);
                goods_comfirm.setClickable(true);
            }
        };
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(requestParam);
    }

    private void refreshSelf() {
        MyToast.show(this, getString(R.string.allgoods_invalid));
    }

    private void processPreOderResult(String cartId, List<DetailGoods> delGoods) {
        if (null != delGoods && !delGoods.isEmpty())
            deleteInvalidGoods(delGoods);
        if (!TextUtils.isEmpty(cartId))
            gotoConfirmOrder(cartId);
        else
            refreshSelf();
    }

    private void gotoConfirmOrder(String cartId) {
        Intent intent = new Intent(this, ConfirmOrderActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, cartId);
        startActivity(intent);
    }

    private void deleteInvalidGoods(List<DetailGoods> delGoods) {
        ShoppingCartHelper.deleteMutilSimpleGoodsItem(this, delGoods);
    }

    private void close() {
        Intent intent = new Intent();
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, detailGoods);
        setResult(RESULT_OK, intent);
        finish();
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private boolean addBuyCar() {
        if (detailGoods.getSelect_sku() != null) {
            int count = Integer.parseInt(goods_nums.getText().toString());
            DetailGoods temp = ShoppingCartHelper.getSingleShoppingItems(detailGoods.getZg_id() + "_" + detailGoods.getSelect_sku().getZps_id(), this);
            if (temp == null) {
                if (dlist.size() + 1 > 10) {
                    MyToast.show(this, getString(R.string.shopping_cart_oversize));
                    return false;
                } else {
                    dlist.add(detailGoods);
                }
            } else {
                if (temp.getCount() + count > 99) {
                    MyToast.show(this, getString(R.string.over_99));
                    return false;
                }
            }
            return ShoppingCartHelper.putMutilShoppingItem(this, detailGoods, count);
        } else {
            MyToast.show(this, getString(R.string.select_goods));
            return false;
        }
    }

    private void refreashBuyCar() {
        if (dlist.size() > 0) {
            goods_car_nums.setVisibility(View.VISIBLE);
        } else {
            goods_car_nums.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        close();
    }
}
